package com.hdu.mockService.handler;

import com.hdu.mockService.annotation.RandomLong;
import org.apache.commons.collections4.CollectionUtils;

import java.lang.reflect.Field;
import java.util.List;

import static com.hdu.mockService.utils.ReflectionUtils.getFieldsByTargetAnnotation;

public class LongMockHandler implements IMockHandler {
    @Override
    public void partitionMock(Object mockObj) {
        List<Field> mockLongFields = getFieldsByTargetAnnotation(mockObj.getClass(), RandomLong.class);
        if (CollectionUtils.isEmpty(mockLongFields)) {
            return;
        }
        for (Field field : mockLongFields) {
            field.setAccessible(true);
            RandomLong randomLong = field.getAnnotation(RandomLong.class);
            try {
                field.set(mockObj, getRandomLong(randomLong.min(), randomLong.max()));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    public long getRandomLong(long min, long max) {
        return min + (long) (Math.random() * (max - min + 1));
    }
}
